package com.cly.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cly.base.contants.CacheKeysConstants;
import com.cly.entity.Course;
import com.cly.entity.CourseNode;
import com.cly.mapper.CourseNodeMapper;
import com.cly.result.JsonRequest;
import com.cly.result.exception.ServiceException;
import com.cly.result.exenum.RequestException;
import com.cly.service.ICourseNodeService;
import com.cly.service.ICourseService;
import com.cly.vo.CourseNodeVo;
import lombok.RequiredArgsConstructor;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * 课节表业务层实现
 *
 * @author 春风能解释
 * <p>
 * 2024-06-06
 */
@Service
@RequiredArgsConstructor
public class CourseNodeServiceImpl extends ServiceImpl<CourseNodeMapper, CourseNode> implements ICourseNodeService {

    /**
     * 科目服务
     */
    private final ICourseService courseService;


    /**
     * 根据条件查询课节表信息
     *
     * @param courseNode 条件
     * @return JSON
     */
    @Override
    @Cacheable(value = CacheKeysConstants.CourseKeys.COURSE_NODE_ARRAY, key = "#root.args")
    public JsonRequest<List<CourseNodeVo>> lookCourseNode(Integer current, Integer size, CourseNode courseNode) {
        IPage<CourseNodeVo> courseNodePage = baseMapper.selectCourseNodePages(new Page<>(current, size), courseNode);
        return JsonRequest.success(courseNodePage.getRecords(), courseNodePage.getTotal());
    }

    /**
     * 新增一条课节表信息
     *
     * @param courseNode 课节表信息
     * @return JSON
     */
    @Override
    @CacheEvict(value = {CacheKeysConstants.CourseKeys.COURSE_NODE_ARRAY, CacheKeysConstants.CourseKeys.COURSE_COUNT}, allEntries = true)
    public JsonRequest<Integer> addOneCourseNode(CourseNode courseNode) {
        Long courseId = courseNode.getCourseId();
        // 判断课程是否存在
        long count = courseService.count(Wrappers.lambdaQuery(Course.class)
                .eq(Course::getId, courseId));
        if (count < 1) {
            return JsonRequest.error(RequestException.NOT_FOUND);
        }
        // 插入课节表信息
        int column = baseMapper.insert(courseNode);
        if (column < 1) {
            throw new ServiceException(RequestException.INSERT_ERROR);
        }
        // 更新课程的课次
        courseService.update(Wrappers.lambdaUpdate(Course.class)
                .eq(Course::getId, courseId)
                .setIncrBy(Course::getNumber, 1));
        return JsonRequest.success(column);
    }

    /**
     * 修改一条课节表信息
     *
     * @param courseNode 课节表信息
     * @return JSON
     */
    @Override
    @CacheEvict(value = {CacheKeysConstants.CourseKeys.COURSE_NODE_ARRAY, CacheKeysConstants.CourseKeys.COURSE_COUNT}, allEntries = true)
    public JsonRequest<Integer> updateOneCourseNode(CourseNode courseNode) {
        CourseNode courseNodeObject = baseMapper.selectById(courseNode.getId());
        if (Objects.isNull(courseNodeObject)) {
            return JsonRequest.error(RequestException.NOT_FOUND);
        }
        Long courseId = courseNode.getCourseId();
        // 判断课程是否存在
        long count = courseService.count(Wrappers.lambdaQuery(Course.class)
                .eq(Course::getId, courseId));
        if (count < 1) {
            return JsonRequest.error(RequestException.NOT_FOUND);
        }
        int column = baseMapper.updateById(courseNode);
        if (column < 1) {
            throw new ServiceException(RequestException.UPDATE_ERROR);
        }
        return JsonRequest.success(column);
    }

    /**
     * 批量删除课节表信息
     *
     * @param ids 课节表id列表
     * @return JSON
     */
    @Override
    @CacheEvict(value = {CacheKeysConstants.CourseKeys.COURSE_NODE_ARRAY, CacheKeysConstants.CourseKeys.COURSE_COUNT}, allEntries = true)
    public JsonRequest<Integer> deleteCourseNodes(List<Long> ids) {
        // 查询课节表信息
        List<CourseNode> courseNodeList = baseMapper.selectBatchIds(ids);
        // 判断待删除的课节表信息是否存在
        if (courseNodeList.size() != ids.size()) {
            return JsonRequest.error(RequestException.NOT_FOUND);
        }
        int column = baseMapper.deleteByIds(ids);
        if (column < 1) {
            throw new ServiceException(RequestException.DELETE_ERROR);
        }
        List<Long> courseId = courseNodeList.stream()
                .map(CourseNode::getCourseId)
                .toList();
        Map<Long, Integer> map = new HashMap<>();
        // 统计课程的课节数
        for (Long id : courseId) {
            Integer count = map.get(id);
            if (Objects.isNull(count)) {
                map.put(id, 1);
            } else {
                map.put(id, count + 1);
            }
        }
        // 更新课程的课节数
        map.forEach((k, v) -> {
            // 课节数更新
            courseService.update(Wrappers.lambdaUpdate(Course.class)
                    .eq(Course::getId, k)
                    .setDecrBy(Course::getNumber, v));
        });
        return JsonRequest.success(column);
    }

}